<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Localstorage</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <div class="wrapper">
        <h2>LOCAL TAPAS</h2>
        <p></p>
        <ul class="plates">
            <li>Loading Tapas...</li>
        </ul>
        <form class="add-items">
            <label for=""></label>
            <input type="text" name="item" id="" placeholder="Item Name" autofocus required>
            <input type="submit" value="+Add Ttem">
        </form>
    </div>
    <script>
        const additems = document.querySelector('.add-items');
        const itemsList = document.querySelector('.plates');
        const items = JSON.parse(localStorage.getItem('items')) || [];

        function populate(plate = [], platesList) {
            platesList.innerHTML = plate.map((plate, i) => `
            <li>
                <input type="checkbox" data-index=${i} id="item${i}"
                ${plate.done?'checked':''}>
                <label for="item${i}">${plate.text}</label>
                </li>
            `).join('');

        }
        console.log(additem);

        function additem(event) {
            // console.log('-------');
            event.preventDefault();
            const text = this.querySelector('[name=item]').value.trim();
            // console.log(text);
            const item = {
                text,
                done: false
            }
            items.push(item);
            // itemsList.innerHTML = items.map(item =>
            //     `
            //     <li>
            //         <label>${item.text}</label>
            //         </li>
            //     `
            // ).join('');
            console.log(JSON.stringify(items));
            localStorage.setItem('items', JSON.stringify(items));
            populate(items, itemsList);

            this.reset();
        }

        function init() {
            const storageitems = JSON.parse(localStorage.getItem('items'))
            if (storageitems.length) {
                // items = [...storageitems]
                // for (let item of storageitems) {
                //     items.push(item)
                // }
                populate(storageitems, itemsList)
            }
        }
        additems.addEventListener('submit', additem);
        init();
    </script>
</body>

</html>